package com.supply.hsa.link.controller;

import com.supply.hsa.link.common.constant.InitConfigData;
import com.supply.hsa.link.common.constant.SystemConstants;
import com.supply.hsa.link.common.dto.HtlSyncFreqDTO;
import com.supply.hsa.link.common.dto.HtlSyncPreDataDTO;
import com.supply.hsa.link.common.dto.SupplyConfigDTO;
import com.supply.hsa.link.common.server.HotelPreSyncServer;
import com.supply.hsa.link.common.server.SupplyConfigServer;
import com.supply.hsa.link.common.util.ApplicationContextUtil;
import com.supply.hsa.link.hotelinfo.server.HotelInfoSyncService;
import com.supply.hsa.link.task.fetch.server.CommonSupplyFetchService;
import com.supply.hsa.link.task.quartz.QuartzManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@Slf4j
@RequestMapping("/init")
public class InitDataController implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private SupplyConfigServer supplyConfigServer;
    @Autowired
    private HotelPreSyncServer hotelPreSyncServer;
    @Autowired
    private QuartzManager quartzManager;
    @Autowired
    private HotelInfoSyncService hotelInfoSyncService;
    @Autowired
    private CommonSupplyFetchService commonSupplyFetchService;

    @ResponseBody
    @RequestMapping(value = "/supplyConfig", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public String querySupplyConfig(){
        List<SupplyConfigDTO> supplyConfigDTOList = supplyConfigServer.queryAllConfigList();
        if(CollectionUtils.isEmpty(supplyConfigDTOList)){
            return "配置为空";
        }
        initALLSupplyConfig(supplyConfigDTOList);

        return "初始化配置完成";
    }

    @ResponseBody
    @RequestMapping(value = "/initFetchHotelQuartz", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public String initFetchHotelQuartz() {
        String result="初始化同步酒店定时器完成";
        try {
            List<HtlSyncFreqDTO> htlSyncFreqDTOS = hotelPreSyncServer.queryAllFreq();
            List<HtlSyncPreDataDTO> htlSyncPreDataDTOS = hotelPreSyncServer.queryALlFreqForSupplyCode();

            if(CollectionUtils.isNotEmpty(htlSyncFreqDTOS) && CollectionUtils.isNotEmpty(htlSyncFreqDTOS)){
                Map<Integer, HtlSyncFreqDTO> freqMap = new HashMap<>(htlSyncFreqDTOS.size());
                for(HtlSyncFreqDTO dto:htlSyncFreqDTOS){
                    freqMap.put(dto.getId(), dto);
                }

                /**
                 * Map<频率id,供应商编码集合>
                 */
                Map<Integer, List<HtlSyncPreDataDTO>> preDataMap = new HashMap<>(10);
                for(HtlSyncPreDataDTO dto:htlSyncPreDataDTOS){
                    if(preDataMap.containsKey(dto.getFreqId())){
                        preDataMap.get(dto.getFreqId()).add(dto);
                    }else{
                        List<HtlSyncPreDataDTO> list = new ArrayList<>();
                        list.add(dto);
                        preDataMap.put(dto.getFreqId(), list);
                    }
                }

                Class<?> jobClass = Class.forName(SystemConstants.FETCHHOTELTASK_JOBCLASS);

                /**
                 * 每一种频率起一个任务，jobGroupName不变的话jobName不能一样
                 */
                for(Integer tempKey:preDataMap.keySet()){
                    if(!freqMap.containsKey(tempKey)){
                        continue;
                    }
                    HtlSyncFreqDTO freqDTO = freqMap.get(tempKey);
                    Map<String,Object> jobMap = new HashMap<>(1);
                    jobMap.put(SystemConstants.FETCHHOTELTASK_MAP_KEY, preDataMap.get(tempKey));
                    quartzManager.addJob(SystemConstants.FETCHHOTELTASK_JOBNAME + freqDTO.getFreqCode(), SystemConstants.FETCHHOTELTASK_JOBGROUP,
                            freqDTO.getFreqCode(), SystemConstants.FETCHHOTELTASK_TRIGGER, jobClass,freqDTO.getCronExpression(), jobMap);
                }
            }
        } catch (ClassNotFoundException e) {
            result="初始化同步酒店定时器失败";
            e.printStackTrace();
        }
        return "初始化同步酒店定时器完成";
    }

    private void initALLSupplyConfig(List<SupplyConfigDTO> supplyConfigDTOList){
        Map<String,Map<String, Map<String, String>>> configMap = new HashMap<String, Map<String,Map<String,String>>>();
        Map<String,Map<String,String>> shareMap = new HashMap<String,Map<String,String>>();
        Map<String,String> infoMap = null;
        Map<String,String> tempMap = null;
        String supplierClass = "" ;
        for (SupplyConfigDTO config : supplyConfigDTOList) {
            if ("shareProduct".equals(config.getMerchantCode())) {
                if (shareMap.containsKey(config.getSupplierCode())) {
                    shareMap.get(config.getSupplierCode()).put(config.getFieldName(), config.getFieldValue());
                } else {
                    tempMap = new HashMap<String,String>();
                    tempMap.put(config.getFieldName(), config.getFieldValue());
                    shareMap.put(config.getSupplierCode(), tempMap);
                }
                continue;
            }

            supplierClass = config.getSupplierClass();
            if (configMap.containsKey(supplierClass)) {
                Map<String, Map<String, String>> supplierConfigMap = configMap.get(supplierClass);

                if (supplierConfigMap.containsKey(config.getMerchantCode())) {
                    supplierConfigMap.get(config.getMerchantCode()).put(config.getFieldName(), config.getFieldValue());
                } else {
                    infoMap = new HashMap<String, String>();
                    infoMap.put(config.getFieldName(), config.getFieldValue());
                    supplierConfigMap.put(config.getMerchantCode(), infoMap);
                }
            } else {
                Map<String, Map<String, String>> supplierConfigMap = new HashMap<String, Map<String,String>>();
                infoMap = new HashMap<String, String>();
                infoMap.put(config.getFieldName(), config.getFieldValue());
                supplierConfigMap.put(config.getMerchantCode(), infoMap);
                configMap.put(supplierClass, supplierConfigMap);
            }
        }
        InitConfigData.configMerchantMap = configMap;
        InitConfigData.shareSupplierMap = shareMap;
    }

    /**
     * 应用启动完执行的所有初始化操作
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        /**
         *
         */
        querySupplyConfig();
        initFetchHotelQuartz();
    }
}
